package com.xy.mainp.huaban.utils;
import android.content.Context;
import android.database.Cursor;
import com.xy.UtilDB;
import com.xy.mainp.model.huaban.SearchHistoryEntity;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by John on 2016/11/17.
 */

public class SearchUtil {
    private static SearchUtil mInstance;
    private static final String TABLENAME = "searchHistory";
    private static final String DBNAME = "XyApp";
    private static Context mContext;
    private UtilDB utilDB;

    private  SearchUtil(Context context){
        utilDB = new UtilDB(context);
        utilDB.open(DBNAME);
        utilDB.createTables(TABLENAME,SearchHistoryEntity.class);
        utilDB.close();
    }

    public static SearchUtil getInstance(Context context){
        if (mInstance == null){
            synchronized (SearchUtil.class){
                if (mInstance == null){
                    mContext = context;
                    mInstance = new SearchUtil(context);
                }
            }
        }
        return mInstance;
    }

    public List<SearchHistoryEntity> searchData(String text){
        utilDB.open(DBNAME);
        List<SearchHistoryEntity> searchHistory = new ArrayList<>();
        if (utilDB.getRows("searchHistory",null,SearchHistoryEntity.class).size() != 0){
            //按时间前后排序
            searchHistory  = utilDB.getRows(TABLENAME,"text like '%"+ text+"%' order by cTime desc ",SearchHistoryEntity.class);
        }
        utilDB.close();
        return searchHistory;
    }

    public List<SearchHistoryEntity> getAllData( ){
        utilDB.open(DBNAME);
        List<SearchHistoryEntity> rows = utilDB.getRows(TABLENAME, null, SearchHistoryEntity.class);
        utilDB.close();
        return rows;
    }


    public void insertData(SearchHistoryEntity entity){
        utilDB.open(DBNAME);
        utilDB.insertRow(TABLENAME, entity);
        utilDB.close();
    }

    public boolean hasData(String text){
        utilDB.open(DBNAME);
        Cursor cursor = utilDB.rawQuery("select * from " + TABLENAME + " where text = ?", text);
        boolean isHas = cursor.moveToNext();
        utilDB.close();
        return isHas;

    }

    public void updateData(SearchHistoryEntity entity,String where,String[] whereArg){
        utilDB.open(DBNAME);
        utilDB.updateRow(TABLENAME,entity,where,whereArg);
        utilDB.close();


    }

    public void clearData(){
        utilDB.open(DBNAME);
        utilDB.clearTable(TABLENAME);
        utilDB.close();
    }
}
